<template>
  <app-page :customNav="true" :login="false">
    <mxp-navbar
      title=""
      homePath="/pages/tab-bar/index1/index1"
      :borderColor="false"
      leftIconColor="#ffffff"
      titleWidth="0px"
      :placeholder="false"
      background="transparent"
    ></mxp-navbar>
    <player></player>
  </app-page>
</template>

<!-- 需要先在 setup（vue 独有的生命周期）执行一遍 -->
<script lang="ts">
  tt.PlayletExtension();
</script>

<script setup lang="ts">
  import { onLoad, onReady } from '@dcloudio/uni-app';
  import { ref, shallowRef } from 'vue';
  import AppPage from '@/components/app-page/app-page.vue';
  import MxpNavbar from '@/mxp-ui/mxp-navbar/mxp-navbar.vue';
  import { autoLogin } from '@/utils/page/user';
  import { useAppStore } from '@/pinia/app';
  import player from './components/player/player.vue';
  import { initDyDramaPlayInfoAxios } from '@/api/drama';
  import { userActionLog } from '@/api/datapoint';
  const appStore = useAppStore();
  const pm = shallowRef<tt.PlayletManager>();
  const tt_episode_id = ref('');
  onLoad((op) => {
    pm.value = tt.getPlayletManager();
    tt_episode_id.value = op?.tt_album_id;
  });

  onReady(() => {
    if (uni.canIUse('PlayletExtension')) {
      initPlayInfo();
    } else {
      uni.showModal({
        title: '暂不支持播放',
        content: '您的抖音APP版本太低,暂不支持播放,请先升级到30.3.0以上版本',
      });
    }
  });

  /**
   * 初始化短剧播放信息
   * @param dramaId - 剧剧目ID
   */
  async function initPlayInfo() {
    try {
      // 未登录则先登录
      !appStore.loginState && (await autoLogin());
      if (!tt_episode_id.value) {
        const info = await pm.value?.getPlayletInfo();
        tt_episode_id.value = info!.albumId;
      }
      const data = {
        thirdDramaId: tt_episode_id.value,
        referralLinkId: appStore?.launchQuery?.referralLinkId,
        channelId: appStore.launchQuery?.channelId || undefined,
        clickid: appStore.launchQuery?.clickid || undefined,
        projectId: appStore.launchQuery.projectid || undefined,
        promotionId: appStore.launchQuery.promotionid || undefined,
        launchQuery: JSON.stringify(appStore?.launchQuery || {}),
      };
      const res = await initDyDramaPlayInfoAxios(data);
      appStore.updateIsIaaFlag(res.data.isIaaFlag);
      appStore.setTwoAdvertFrame(res.data.twoAdvertFrame);
      pm.value?.setCatalog(res.data);
      return Promise.resolve(res.data);
    } catch (error) {
      console.log('error====', error);
      userActionLog({
        userId: appStore.userInfo?.userId,
        data: JSON.stringify(appStore?.launchQuery || {}),
        eventType: 'TOUTIAO_PLAYINFO_INIT',
        msg: JSON.stringify(error),
      });
      return Promise.reject(error);
    }
  }
</script>
